package com.sunnada.nginx.bean.nginx.http.upstream;

import com.alibaba.fastjson.JSON;
import com.github.odiszapc.nginxparser.*;
import com.sunnada.nginx.exception.CustonException;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class Upstream {
    @ApiModelProperty(value = "上游配置名称",required = true)
    private String name;
    @ApiModelProperty(value = "配置服务器列表")
    private List<Server> servers = new ArrayList<>();

    public Upstream(){}

    public Upstream(NgxBlock block){
        this.name = block.getValue();
        Collection<NgxEntry> entries = block.getEntries();
        for (NgxEntry entry : entries) {
            if (entry instanceof NgxComment){
                continue;
            }
            NgxParam ngxParam = (NgxParam)entry;
            this.servers.add(new Server(ngxParam.getValues()));
        }
    }

    public boolean addServer(Server server){
        return servers.add(server);
    }

    /**
     * 校验这个对象的有效性
     * @return
     */
    public boolean vali() throws CustonException {
        if (StringUtils.isBlank(name)) throw new CustonException("upstream的名字为空");
        if (servers.size()==0) throw new CustonException("upstream中至少包含一个server");
        for (Server server : servers) {server.vali();}
        return true;
    }

    /**
     * 将对象转为NgxBlock对象
     * @return
     */
    public NgxBlock toNgxBlock(){
        NgxBlock block = new NgxBlock();
        block.addValue(new NgxToken(getToken()));
        block.addValue(name);
        for (Server server : servers) {
            block.addEntry(server.toNgxParam());
        }
        return block;
    }

    public String toJson(){
       return JSON.toJSONString(this);
    }

    public String getToken(){
        return "upstream";
    }
}
